package com.dankegongyu.lib.paging;

import com.dankegongyu.lib.base.BaseAppActivity;
import com.dankegongyu.lib.common.paging.BasePagingViewModel;
import com.dankegongyu.lib.common.paging.PagingData;
import com.dankegongyu.lib.common.paging.PagingState;
import com.dankegongyu.lib.common.paging.PagingView;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;

/**
 * @author wupuquan
 * @version 1.0
 * @since 2020/4/16 16:25
 */
public abstract class BasePagingActivity<VM extends BasePagingViewModel, T> extends BaseAppActivity implements PagingView {

    private VM mPagingViewModel;

    @Override
    public void initPresenter() {
        mPagingViewModel = createPagingViewModel();
        if (mPagingViewModel != null) {
            //noinspection unchecked
            mPagingViewModel.getPagingDataLiveData().observe(this, new Observer() {
                @Override
                public void onChanged(Object o) {
                    if (o instanceof PagingData) {
                        //noinspection unchecked
                        onPagingDataChanged((PagingData<T>) o);
                    }
                }
            });
            //noinspection unchecked
            mPagingViewModel.getPagingStateLiveData().observe(this, new Observer() {
                @Override
                public void onChanged(Object o) {
                    if (o instanceof PagingState) {
                        onPagingStateChanged((PagingState) o);
                    }
                }
            });
        }
    }

    protected abstract VM createPagingViewModel();

    protected abstract void onPagingViewModelCreated();

    public VM getPagingViewModel() {
        return mPagingViewModel;
    }

    protected abstract void onPagingDataChanged(@NonNull PagingData<T> pagingData);

    private void onPagingStateChanged(@NonNull PagingState pagingState) {
        switch (pagingState) {
            case LOADING:
                showPagingLoading();
                break;
            case SUCCESS:
                showPagingSuccess();
                break;
            case ERROR:
                showPagingError(pagingState.getMessage());
                break;
            case EMPTY:
                showPagingEmpty();
                break;
            case NO_MORE_DATA:
                showPagingNoMore();
                break;
            case LOAD_MORE_FAILED:
                showPagingLoadMoreFailed();
                break;
        }
    }
}
